// pages/orderMeal/index.js
// 后端配置
import {
  BasicUrl,
  request
} from "../../api/config.js"
Page({
  /**
   * 页面的初始数据
   */
  data: {
    BasicUrl: '',
    // 是否选择了商品
    isSelectProduct: false,
    // 购物车商品数量
    card: {
      price: 0,
      num: 0,
      // 加料价钱
      chargePrice: 0,
      // 选择的商品数量
      select_num: 1,
    },
    // 购物车信息
    cardData: [],
    // 查看购物车详情
    showCardDetail: false,
    // 是否显示选择店面
    showStore: false,
    // 显示选择商品规格
    showGoodsDetail: false,
    // 是否收藏店面
    Collect: false,
    // 左侧导航
    mainActiveIndex: 0,
    items: [],
    // 商品规格
    goods_attr: [
      // {
      //   attr_name: '温度',
      //   attr_item: [{
      //       name: '常温',
      //       select: true
      //     },
      //     {
      //       name: '冷',
      //     },
      //     {
      //       name: '热',
      //     },
      //   ]
      // },
      // {
      //   attr_name: '甜度',
      //   attr_item: [{
      //       name: '不另外加糖',
      //       select: true
      //     },
      //     {
      //       name: '3分糖',
      //     },
      //     {
      //       name: '半糖',
      //     },
      //     {
      //       name: '8分糖',
      //     },
      //     {
      //       name: '全糖',
      //     },
      //   ]
      // },
      // {
      //   attr_name: '加料',
      //   attr_item: [{
      //       name: '珍珠',
      //       price: '2.00'
      //     },
      //     {
      //       name: '脆啵啵',
      //       price: '3.00'
      //     },
      //     {
      //       name: '西米',
      //       price: '2.00'
      //     },
      //     {
      //       name: '红豆',
      //       price: '2.00'
      //     },
      //   ]
      // },
    ],
    // 选择的商品规格
    select_attr_data: '',
    activeId: [],
    // 选择的商品
    select_data_info: {},
    // 控制右侧商品列表的滚动条位置
    scrollIntoViewId: 'Goods0',
    // 查看商家信息
    isShowStoreInfo: false,
    // 当前商家
    currStore: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    wx.showLoading({
      title: '加载中...',
    })
    this.getlist()
    // 处理参数值  
    this.setData({
      BasicUrl: BasicUrl
    })
    wx.hideLoading()
  },
  // 获取商品信息
  async getlist() {
    wx.showLoading({
      title: '加载中...',
    })
    await request('/api/goods/wx_get_list', 'POST', {}, false).then(({
      data
    }) => {
      console.log(data);
      data.data.forEach(item => {
        item.list.forEach(goods => {
          goods.select_num = 0
        })
      })
      if (data.code == 200) {
        this.setData({
          items: data.data
        })
        wx.setStorageSync('goods_list', JSON.stringify(data.data))
      } else {
        wx.showToast({
          title: '获取商品信息失败',
        })
      }
      wx.hideLoading()
    })
  },
  // 左侧商品导航
  onClickNav(e) {
    let idx = e.detail.index
    console.log(idx);
    this.setData({
      mainActiveIndex: idx
    })
    this.setData({
      scrollIntoViewId: 'Goods' + idx
    })
  },
  // 去结算
  toBalance() {
    let has_login = wx.getStorageSync('user_info')
    if (has_login) {
      wx.setStorageSync('card_data', this.data.cardData)
      wx.navigateTo({
        url: "/pages/balance/index",
        data: {
          cardData: this.data.cardData
        }
      })
    } else {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      wx.switchTab({
        url: '/pages/mine/index',
      })
    }
  },
  // 去切换商家
  toStoreMap() {
    this.setData({
      showStore: false
    })
    wx.navigateTo({
      url: "/pages/checkStore/index",
      events: {
        curr_store: function (data) {
          console.log(data);
        }
      }
    })
  },
  // 修改购物车商品数量
  change_card_item_num(e) {
    let num = e.detail
    let {
      index
    } = e.currentTarget.dataset
    if (num == 0) {
      this.data.items.forEach(item => {
        item.list.forEach(good => {
          if (good.goods_id == this.data.cardData[index].goods_id) {
            good.select_num = 0
          }
        })
      })
      this.setData({
        items: this.data.items
      })
      this.data.cardData.splice(index, 1)
      if (this.data.cardData.length == 0) {
        this.setData({
          showCardDetail: false,
          isSelectProduct: false
        })
      }
    } else {
      this.data.items.forEach(item => {
        item.list.forEach(good => {
          if (good.goods_id == this.data.cardData[index].goods_id) {
            good.select_num = num
          }
        })
      })
      this.setData({
        items: this.data.items
      })
      this.data.cardData[index].num = num
    }
    this.setData({
      cardData: this.data.cardData
    })
    this.get_cardData_info()

  },
  // 清空购物车
  remove_card(){
    let goods_list = JSON.parse(wx.getStorageSync('goods_list'))
    this.setData({
      cardData:[],
      showCardDetail:false,
      isSelectProduct:false,
      items:goods_list
    })

    // this.getlist()
  },
  // 去搜索
  toSearch() {
    wx.navigateTo({
      url: "/pages/search/index"
    })
  },
  // 查看商家公告信息
  showStoreInfo() {
    this.setData({
      isShowStoreInfo: true
    })
  },
  // 关闭公告
  closeAnnouncement() {
    this.setData({
      isShowStoreInfo: false
    })
  },
  // 查看选择的商品详情
  showSelectGoodsDetail() {
    this.setData({
      showCardDetail: !this.data.showCardDetail
    })
  },
  // 关闭选择的商品详情
  CloseCardDetail() {
    this.setData({
      showCardDetail: false
    })
  },
  // 选择商品规格
  selectAttr(e) {
    // 获取传参
    let select_data = e.currentTarget.dataset
    // 获取点击的是第几个商品规格的下标
    let select_attr_idx = this.data.goods_attr.findIndex(item => item.attr_name == select_data.attr.attr_name)
    // 遍历选择的商品规格下标修改选中效果
    this.data.goods_attr[select_attr_idx].attr_item.forEach((item, index) => {
      if (item.name == select_data.attrval.name) {
        item.select = true
      } else {
        item.select = false
      }
      // 加料项不必选
      if (select_data.attr.attr_name == '加料' && select_data.attrval.select == true) {
        item.select = false
      }
    })
    // 更新选中的商品规格
    this.setData({
      goods_attr: this.data.goods_attr
    })
    // 更新已选的商品规格以及计算加料价格
    this.updateGoodsAttr()
  },
  // 加入购物车
  addCard() {
    let price = Number(this.data.card.price) + Number(this.data.select_data_info.goods_price)
    let num = Number(this.data.card.num) + this.data.select_data_info.select_num
    // 判断购物车里有无相同商品，有则叠加数量，无则添加
    let hasGoods = this.data.cardData.findIndex(item => item.goods_id == this.data.select_data_info.goods_id)
    if (hasGoods == -1) {
      this.data.cardData.push({
        ...this.data.select_data_info,
        attr: this.data.select_attr_data,
        attr_price: this.data.card.chargePrice,
        num: this.data.card.select_num
      })
      console.log(this.data.cardData);
      this.data.items.forEach((item) => {
        item.list.forEach((good) => {
          if (good.goods_id == this.data.select_data_info.goods_id) {
            good.select_num = this.data.card.select_num
          }
        })
      })
      console.log(this.data.items);
      this.setData({
        'card.price': price,
        'card.num': num,
        showGoodsDetail: false,
        isSelectProduct: true,
        cardData: this.data.cardData,
        items: this.data.items
      })
    } else {
      this.data.cardData[hasGoods].num += this.data.card.select_num
      this.data.items.forEach((item) => {
        item.list.forEach((good) => {
          if (good.goods_id == this.data.select_data_info.goods_id) {
            good.select_num += this.data.card.select_num
          }
        })
      })
      this.setData({
        cardData: this.data.cardData,
        showGoodsDetail: false,
        isSelectProduct: true,
        items: this.data.items
      })
    }
    this.get_cardData_info()
  },
  // 计算底部购物车商品总数
  get_cardData_info() {
    let count = 0
    let total_price = 0
    this.data.cardData.forEach(item => {
      count += item.num
      total_price += ((item.goods_price - (item.goods_preferential * 1)) + (item.attr_price * 1)) * item.num
    })
    this.setData({
      'card.num': count,
      'card.price': total_price
    })
  },
  // 确认选择门店
  verify() {
    this.setData({
      showStore: false
    })
  },
  // 切换选择商品步进器
  change_select_num(e) {
    console.log(e.detail);
    this.setData({
      'card.select_num': e.detail
    })
  },
  // 收藏
  changeCollect(e) {
    console.log(e.currentTarget.dataset.info);
    let store_id =e.currentTarget.dataset.info.id
    let is_collect =  e.currentTarget.dataset.info.is_collect == 1 ? 0 : 1
    let user_id =wx.getStorageSync('user_info') ?  JSON.parse(wx.getStorageSync('user_info')).user_id : ''
    if(!user_id){
       wx.showToast({
        title: '请先登录',
        icon:'none'
      })
      return wx.switchTab({
        url: '/pages/mine/index',
      })
    }
    request('/api/store/collection_store','post',{user_id,store_id,is_collect},true).then(({data})=>{
      console.log(data);
      if(data.code == 200){
        let store_info = JSON.parse(wx.getStorageSync('store_info'))
        if (is_collect == 1) {
          wx.showToast({
            title: `收藏成功`,
            icon: 'none'
          });
          store_info.is_collect = 1
          this.setData({
            currStore:store_info
          })
        } else {
          wx.showToast({
            title: `已取消收藏`,
            icon: 'none'
          });
          store_info.is_collect = 0
          this.setData({
            currStore:store_info
          })
        }
      }else{
        wx.showToast({
          title: '收藏失败',
          icon: 'none'
        })
      }
    })
  },
  // 关闭商品选择
  CloseGoodsDetail() {
    this.setData({
      showGoodsDetail: false
    })
  },
  // 选择商品
  SelectGoods(e) {
    console.log(e);
    let goodsData = e.currentTarget.dataset.goodsinfo
    // 恢复card的信息统计
    this.setData({
      'card.chargePrice': 0,
      'card.select_num': 1
      // card:{
      //   num:0,
      //   price:0,
      //   chargePrice:0,
      //   select_num: 1
      // }
    })
    this.setData({
      showGoodsDetail: true,
      select_data_info: goodsData
    })
    console.log(goodsData);
    // 请求商品规格信息
    this.get_goods_specification(goodsData.specification_ids)

  },
  // 请求商品规格信息
  get_goods_specification(specification_ids) {
    request('/api/goods/wx_get_goods_specification', 'POST', {
      specification_ids
    }, false).then(({
      data
    }) => {
      console.log(data.data);
      this.setData({
        goods_attr: data.data
      })
      // 更新已选的商品规格以及计算加料价格
      this.updateGoodsAttr()
    })
  },
  // 更新已选的商品规格以及计算加料价格
  updateGoodsAttr() {
    let select_attr = ''
    this.data.goods_attr.forEach(item => {
      item.attr_item.forEach(attr => {
        if (attr.select) {
          select_attr += attr.name + ','
        }
        if (item.attr_name == '加料' && attr.select) {
          this.setData({
            'card.chargePrice': attr.price
          })
        }
      })
    })
    this.setData({
      select_attr_data: select_attr
    })
  },
  // 返回首页
  goHome() {
    wx.switchTab({
      url: '/pages/index/index'
    })
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    this.setData({
      showStore: true
    })
    if(wx.getStorageSync('goods_list')){
      let goods_list = JSON.parse(wx.getStorageSync('goods_list'))
      this.setData({
        items:goods_list
      })
    }else{
      this.getlist()
    }
    // 计算商家距离
    // this.getDistance()
  },
  getDistance() {
    // 当前定位
    let {
      latitude,
      longitude
    } = wx.getStorageSync('location')
    let currAdd = latitude + ',' + longitude
    // 商家位置
    let store_info = JSON.parse(wx.getStorageSync('store_info'))
    let storeAdd = store_info.latitude + ',' + store_info.longitude
    let [lat1, lng1] = currAdd.split(',')
    let [lat2, lng2] = storeAdd.split(',')
    var radLat1 = this.Rad(lat1);
    var radLat2 = this.Rad(lat2);
    var a = radLat1 - radLat2;
    var b = this.Rad(lng1) - this.Rad(lng2);
    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
    s = s * 6378.137;
    s = Math.round(s * 10000) / 10000;
    s = s.toFixed(2) //保留两位小数
    console.log('经纬度计算的距离:' + s)

    //  计算出来重新赋值到本地缓存  distance为距离
    store_info.distance = s
    this.setData({
      currStore: store_info
    })
    // console.log(store_info);
    wx.removeStorageSync('store_info')
    wx.setStorageSync('store_info', JSON.stringify(store_info))
  },
  Rad: function (d) { //根据经纬度判断距离
    return d * Math.PI / 180.0;
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getTabBar().setData({
      active: 1
    })
    wx.showLoading({
      title: '加载中...',
    })
    this.getDistance()
    let hasCreateOrder = wx.getStorageSync('createOrder') 
    console.log('hasCreateOrder',hasCreateOrder);
    if(!hasCreateOrder){
      this.setData({
        isSelectProduct:false
      })
      if(wx.getStorageSync('store_info')){
        let currStore = JSON.parse(wx.getStorageSync('store_info'))
        this.setData({
          store_info: currStore
        })
      }else{
        this.getStoreInfo()
      }
      // this.getlist()
      // if(wx.getStorageSync('goods_list')){
      //   let goods_list = JSON.parse(wx.getStorageSync('goods_list'))
      //   this.setData({
      //     items:goods_list
      //   })
      // }
      
    }
    wx.hideLoading()
  },
   // 获取商家信息并存入本地缓存
   getStoreInfo() {
    let user_id =wx.getStorageSync('user_info') ? JSON.parse(wx.getStorageSync('user_info')).user_id  : ''
    console.log('user_id',wx.getStorageSync('user_info'));
    request('/api/store/get_store_info', "POST", {
      store_id: 1,
      user_id
    }, false).then(({
      data
    }) => {
      console.log(data);
      if (data.code == 200) {
        data.data.store_imgs = data.data.store_imgs.split(',')
        wx.setStorageSync('store_info', JSON.stringify(data.data))
        this.setData({
          store_info: data.data
        })
      } else {
        wx.showToast({
          title: '获取商家信息失败',
          icon: 'error'
        })
        console.log("获取商家信息失败");
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})